<?php
namespace backend\controllers;
use Yii;
use backend\models\SysItem;
use backend\models\SysItemSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use backend\models\GrpClass;
use yii\helpers\ArrayHelper;

use yii\web\UploadedFile;
use backend\models\UploadForm;
use PHPThumb\GD;
use backend\models\Image;
use backend\models\Fabric;
use backend\models\Material;
use backend\models\ItemPreview;
use backend\models\ItemPreviewAngle;

use yii\web\ForbiddenHttpException;


use liangzoe\mobilesmser\TextSmser;
use backend\models\PrfType;
use backend\models\GrpColor;
use backend\models\GrpSpace;
use backend\models\GrpStyle;
use backend\models\GrpPrice;
use backend\models\SysItemColor;
use backend\models\SysItemSpace;
use backend\models\SysItemStyle;
use backend\models\SysItemPrices;
use backend\models\SysItemPlace;
use backend\models\SysItemSery;
use backend\models\SysItemPricesSearch;
use backend\models\GrpSery;
use backend\models\PrfConfig;
use backend\models\SysItemPricesEx;
use backend\models\SysItemInfoEx;
use backend\models\SysItemSize;
use backend\models\GrpBrand;
use backend\models\AdminInfo;
use backend\models\TaozhuangPosSearch;
use backend\models\TaozhuangPos;
use dektrium\user\models\query\all;
use backend\models\GrpBrandCity;
use frontend\models\GrpCity;
use backend\models\GrpBrandHead;
use backend\models\BaseSysPreview;
use common\components\phpexecel\CommonFunc;
use common\components\phpexecel\ItemCommonFunc;
use yii\data\Pagination;
use yii\data\ArrayDataProvider;
/**
 * SysItemController implements the CRUD actions for SysItem model.
 */
class SysItemController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    public function beforeAction($action)
    {
    	//如果未登录，则直接跳转
    	if(Yii::$app->user->isGuest){
    		return $this->redirect(['/site/login']);
    	}

    	$action = Yii::$app->controller->action->id;
    	$controller = Yii::$app->controller->id;
    	if(\Yii::$app->user->can('item-manage') || \Yii::$app->user->can('item-open')){
    		if($action == 'create' && AdminInfo::check_create('create') == true){
				return true;
			}
    		if($this->_access($action) == true){
    			return true;
    		}
    		
    		if(in_array($action,array('view','update','imagedefault','imagefabric','imagematerial')))
    			$item_id = isset($_REQUEST['id']) ? trim($_REQUEST['id']) : 0;
    		else
    			$item_id = isset($_REQUEST['item_id']) ? trim($_REQUEST['item_id']) : 0;
    		
    		if($item_id != 0){
    			$model = $this->findModel($item_id);
    			if($action == 'view' && \Yii::$app->user->can('yys-view-platform'))
    				return true;
    			if($action == 'view' && AdminInfo::check_user_id(Yii::$app->user->identity->id,$model['admin_id'],'view')){
    				return true;
    			}elseif ($action != 'view' && AdminInfo::check_user_id(Yii::$app->user->identity->id,$model['admin_id'],'edit'))
    				return true;
    			else{
    				throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
    			}
    		}
    	}else{
    		throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
    	}
    }
    //允许访问
    function _access($action){
    	$action_list = array(
    		'index',
    	    'update-size',
    		'show-brand',
    		'saleattr',
    		'selectsery',
    		'selectclass1',
    		'selectclass2',
    	    'generate-qrcode',
    	    'change-material',
    	    'change-fabric',
    	    'change-coating',
	    	'change-saleattr',
    		'set-discount-price-batch',
    		'delete-brand',
    		'select-brand',
    		'delete-item-info-ex',
    		'delete-custom-price',
    		'imageitem',
    		'delete-angle',
    		'delete-preview',
    		'change-toptime',
    		'saleattr',
    		'show-brand',
    		'getcityid',
    		'checked',
    		'brand',
    		'city',
    		'add-gjj-code',
    		'change-custom-price',
    	    'get-preview',
    	    'find-tzimg',
    		'upload',
    	    'selectbrandbyheadgrp',
    	    'export-list',
    	    'export-data',
    	    'update-price',
            'delete-sys-item'
    	);
    	if(in_array($action, $action_list)){
    		return true;
    	}
    }
    //根据单品ID查询相关透视图的ID
    public function actionFindTzimg()
    {
        return $this->render('find-tzimg');
    }
    public function actionGetPreview()
    {
        $getId = Yii::$app->request->post('id');
        if($getId == null) {
            return [];
        }
        $getType = Yii::$app->request->post('type');
        if ($getType == 'item') {
            $arr = BaseSysPreview::find()->select(['img_tz_id'])->where(['item_id'=>$getId])->asArray()->column();
        }else if ($getType == 'preview') {
            $arr = BaseSysPreview::find()->select(['item_id'])->where(['img_tz_id'=>$getId])->asArray()->column();
        }else if ($getType == 'pos') {
            $arr = TaozhuangPos::find()->select(['img_id','item_id'])->where(['id'=>$getId])->asArray()->all();
        }
        
        echo json_encode($arr);
    }
    //*******************品牌显示*******************
    //ajax获取城市
    public function actionCity()
    {
        $data=[];
        if(Yii::$app->request->isAjax&&Yii::$app->request->post('id'))
        {
            if (Yii::$app->request->post('q')=='city')
            {
                $value=GrpCity::city(intval(Yii::$app->request->post('id')));
            }
            elseif(Yii::$app->request->post('q')=='area2')
            {
                $value=GrpCity::area3(intval(Yii::$app->request->post('id')));
            }
            elseif (Yii::$app->request->post('q')=='area')
            {
                $value=GrpCity::area(intval(Yii::$app->request->post('id')));
            }
            $data['city'] = $value ;
            $getBrand = json_decode(Yii::$app->request->post("nameId"),true);
            $GetCityid = GrpBrandCity::find()->where(['brand_id'=>$getBrand])->asArray()->all();
            if(empty($GetCityid)){
                $data['name'] = ["无"];
                echo json_encode($data,true);
                return;
            }
            foreach ($GetCityid as $key=>$val){
                $GetCityids[$key] = $val["city_id"];
            }
            
            $GetCityname = GrpCity::find()->where(['in','id',$GetCityids])->all();
            foreach ($GetCityname as $key=>$val){
                $GetCitynames[$key] = $val["name"];
            }
             $data['name']=$GetCitynames;
             echo json_encode($data,true);
        }
    }
    //ajax获取品牌名
    public function actionBrand()
    {
        if(Yii::$app->request->isAjax&&Yii::$app->request->post('id')){
            $value=GrpBrandCity::brand(intval(Yii::$app->request->post('id')));
        }
        echo json_encode($value,JSON_UNESCAPED_UNICODE);
    }
    //ajax获取选中的城市
    public function actionChecked()
    {
        $data = [];
        $getBrand = json_decode(Yii::$app->request->post("id"),true);
        $GetCityid = GrpBrandCity::find()->where(['brand_id'=>$getBrand])->asArray()->all();
        if(empty($GetCityid)){
            $data['name'] = ["无"];
            print_r(json_encode($data,true));
            return;
        }
        foreach ($GetCityid as $key=>$val){
            $GetCityids[$key] = $val["city_id"];
        }
        $data['id'] = $GetCityids;
        $GetCityname = GrpCity::find()->where(['in','id',$GetCityids])->all();
        foreach ($GetCityname as $key=>$val){
            $GetCitynames[$key] = $val["name"];
        }
        $data['name']=$GetCitynames;
        echo json_encode($data,JSON_UNESCAPED_UNICODE);
    }
    public function actionGetcityid()
    {
        $data = [];
        if (Yii::$app->request->isPost) {
            $getflag = json_decode(Yii::$app->request->post("flag"),true);
            $getnameId =json_decode(Yii::$app->request->post("nameId"),true);
            $getcityId =json_decode(Yii::$app->request->post("cityid"),true);
            if($getflag=="1"){
                $grpBrandCity = GrpBrandCity::findOne(['brand_id'=>$getnameId]);
                if (empty($grpBrandCity)){
                    $data['statu'] = 0;
                }else{
                    $grpBrandCity->delete();
                    $data['statu'] = 0; 
                }
            }else{
                $gbc = new GrpBrandCity();
                if(empty($gbc->brand_id)){
                    $gbc->brand_id = $getnameId;
                    $gbc->city_id =  $getcityId;
                    $gbc->save();
                    $data['statu'] = 1;
                }else{
                    $data['statu'] = 1;
                }
            }
            $GetCityid = GrpBrandCity::findAll(['brand_id'=>$getnameId]);
            if(empty($GetCityid)){
                $data['name'] = ["无"];
                print_r(json_encode($data,true));
                return;
            }
            foreach ($GetCityid as $key=>$val){
                $GetCityids[$key] = $val["city_id"];
            }
            $data['id'] = $GetCityids;
            $GetCityname = GrpCity::find()->where(['in','id',$GetCityids])->all();
            foreach ($GetCityname as $key=>$val){
                $GetCitynames[$key] = $val["name"];
            }
            $data['name']=$GetCitynames;
            print_r(json_encode($data,true));
        }
    }
    public function actionShowBrand()
    {
        $model=new GrpBrandCity();
        $temp = GrpBrandHead::find()->asArray()->all();
        foreach ($temp AS $key =>$val){
            $brandName[$key] = ['id'=>$val['id'],'name'=>$val['name']];
        }
        $model->brand = GrpBrand::find()->where(['in','head_grp',]);
        $province = GrpCity::province();
        return $this->render('show-brand',[
            'model' => $model,
            'brandName' => $brandName,
            'province'=>$province
        ]);
    }
    //*******************品牌显示*******************
    
    /**
     * Lists all SysItem models.
     * @return mixed
     */
    public  function  actionSaleattr()
    {
        $searchModel = new TaozhuangposSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->get());
        
        return $this->render('saleattr', [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }
    public function actionChangeSaleattr(){
        if (Yii::$app->request->isPost) {
            $getId = json_decode(Yii::$app->request->post("data"),true);
            $TaozhuangPos = TaozhuangPos::find()->where(['in','id',$getId['id']])->all();
            switch ($getId['state'])
            {
            case 0:
                foreach ($TaozhuangPos as $key => $val){
                    $TaozhuangPos[$key]->pay_state = 0;
                    $TaozhuangPos[$key]->save();
                }
              break;
            case 1:
            foreach ($TaozhuangPos as $key => $val){
                    $TaozhuangPos[$key]->pay_state = 1;
                    $TaozhuangPos[$key]->save();
                }
              break;
            case 2:
                foreach ($TaozhuangPos as $key => $val){
                    $TaozhuangPos[$key]->pay_state = 2;
                    $TaozhuangPos[$key]->save();
                }
              break;
            }
        }
    }
    
    public function actionIndex()
    {
        
        $searchModel = new SysItemSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    public function actionChangeToptime()
    {
        
        if (Yii::$app->request->isPost) {
            $getId = Yii::$app->request->post("id");
            $getFlag = Yii::$app->request->post("flag");
            $topTime = SysItem::findOne(['id'=>$getId]);
            if($getFlag == "false"){
                $topTime->top_time = time();
                $topTime->save();
                echo "1";
            }else if($getFlag == "true"){
                $topTime->top_time='0';
                $topTime->save(); 
                echo "0";
            }
        }
    }
    /**
     * Displays a single SysItem model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
    	$this->layout = 'main_small';
    //	$model = $this->findModel($id);
    $sql="select grp_unit.name unit_name,sys_item.* from sys_item left join grp_unit on grp_unit.id=sys_item.unit_id
         where sys_item.id=:id
        ";
       // $model = SysItem::find()->with()->where("id=:id",array(":id"=>$id))->one();
        $model=SysItem::findBySql($sql,array(":id"=>$id))->one();
    	$color = SysItemColor::find()->where(['item_id' =>$id])->all();
    	foreach ($color as $value){
    		$model->color_list .= $value->grpName->name.',';
    	}
    	$style = SysItemStyle::find()->where(['item_id' =>$id])->all();
    	foreach ($style as $value){
    		$model->style_list .= $value->grpName->name.',';
    	}
    	$space = SysItemSpace::find()->where(['item_id' =>$id])->all();
    	foreach ($space as $value){
    		$model->space_list .= $value->grpName->name.',';
    	}
    	$place = SysItemPlace::find()->where(['item_id' =>$id])->all();
    	foreach ($place as $value){
    		$model->place_list .= $value->grpName->name.',';
    	}
    	$sery = SysItemSery::find()->where(['item_id' =>$id])->all();
    	foreach ($sery as $value){
    		$model->sery_list .= $value->grpName->name.',';
    	}
    	
    	$status_array =array('0'=>'编辑','1'=>'上架','2'=>'下架','3'=>'删除');  	
    	$model->app_return = isset($status_array[$model->app_return])?$status_array[$model->app_return]:$model->app_return;
    	
        return $this->render('view', [
            'model' => $model,
        ]);
    }
    /**
     * 从数据库中查出数据并转换为数组
     * @param unknown $item_id
     * @param unknown $model
     * @param unknown $field
     * @return multitype:
     */
    public function get_ext($model,$field)
    {
    	$arr = array();
    	foreach ($model as $value){
    		array_push($arr, $value[$field]);
    	}
    	return $arr;
    }

    public function add_ext($item_id,$color_list,$style_list,$space_list,$place_list,$sery_list)
    {
    	if(!empty($color_list)){
	    	foreach ($color_list as $value)
	    	{
	    		$model_color = new SysItemColor();
	    		$model_color->item_id = $item_id;
	    		$model_color->color_id = $value;
	    		$model_color->save();
	    	}
    	}
    	if(!empty($style_list)){
    		foreach ($style_list as $value)
    		{
    			$model_style = new SysItemStyle();
    			$model_style->item_id = $item_id;
    			$model_style->style_id = $value;
    			$model_style->save();
    		}
    	}
    	if(!empty($space_list)){
	    	foreach ($space_list as $value)
	    	{
	    		$model_space = new SysItemSpace();
	    		$model_space->item_id = $item_id;
	    		$model_space->space_id = $value;
	    		$model_space->save();
	    	}
    	}
    	if(!empty($place_list)){
    		foreach ($place_list as $value)
    		{
    			$model_place = new SysItemPlace();
    			$model_place->item_id = $item_id;
    			$model_place->place_id = $value;
    			$model_place->save();
    		}
    	}
    	if(!empty($sery_list)){
    		foreach ($sery_list as $value)
    		{
    			$model_sery = new SysItemSery();
    			$model_sery->item_id = $item_id;
    			$model_sery->sery_id = $value;
    			$model_sery->save();
    		}
    	}

    }
    /**
     * Creates a new SysItem model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new SysItem();	
        if ($model->load(Yii::$app->request->post())) {
            if($model->validate()){
                if(empty($model->class_id)){$model->class_id = $model->class2;}
                
                $model->create_uid = Yii::$app->user->identity->id;//创建单品的用户id
                $model->create_at = time();//创建单品的时间
                $model->admin_id = Yii::$app->user->identity->id;
                if($model->app_return == '2'){
                    TaozhuangPos::updateAll(['pay_state'=>0],"item_id={$model->id}");
                }
                $model->save();
                $this->add_ext($model->id, $model->color_list, $model->style_list, $model->space_list, $model->place_list, $model->sery_list);
                
                return $this->redirect(['view', 'id' => $model->id]);
           }else{
               echo '<script type="text/javascript">alert("验证未通过");</script>';
               return $this->redirect(['create']);
           }
        	//echo '<script type="text/javascript">opener.location.reload();</script>';
           
        } else {
            
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

   
    /**
     * Updates an existing SysItem model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
    	
    	$this->layout = 'main_small';
        $model = $this->findModel($id);

	    	$old_class_id = $model->class_id;
	    	$old_brand_id = $model->brand_id;
	        //显示已选中的checkbox
	        $color = SysItemColor::find()->where(['item_id' =>$id])->asArray()->all();     
	        $style = SysItemStyle::find()->where(['item_id' =>$id])->asArray()->all();      
	        $space = SysItemSpace::find()->where(['item_id' =>$id])->asArray()->all();
	        $place = SysItemPlace::find()->where(['item_id' =>$id])->asArray()->all();
	        $sery = SysItemSery::find()->where(['item_id' =>$id])->asArray()->all();
	     
	        $model->color_list = $this->get_ext($color, 'color_id');
	        $model->style_list = $this->get_ext($style, 'style_id');
	        $model->space_list = $this->get_ext($space, 'space_id');
	        $model->place_list = $this->get_ext($place, 'place_id');
	        $model->sery_list = $this->get_ext($sery, 'sery_id');
	
			
	        if ($model->load(Yii::$app->request->post())&&$model->validate()) {   	
	        	if($model->app_return == '1'){
	        		$preview = ItemPreview::findAll(['item_id'=>$model->id]);
	        		if(empty($preview)){
	        			echo '<script type="text/javascript">alert("没有面料材质对应图的单品不能上架");</script>';
		        		return $this->render('update', [
			               'model' => $model,
			         	]);
	        		}
	        		if(empty($model->QRcode))    SysItem::generateQRcode($id);//上架时生成二维码
	        	}
	        	if(empty($model->class_id)){$model->class_id = $model->class2;}
	        	
	        	if($model->app_return == '0' || $model->app_return == '2' || $model->app_return == '3'){
	        		TaozhuangPos::updateAll(['pay_state'=>0],"item_id={$model->id}");
	        	}
	        	$model->save();
	        	//echo '<script type="text/javascript">alert("刷新页面");opener.location.reload();</script>';
	        	//修改时先删除item_id的数据
	        	SysItemColor::deleteAll(['item_id' => $model->id]);
	        	SysItemStyle::deleteAll(['item_id' => $model->id]);
	        	SysItemSpace::deleteAll(['item_id' => $model->id]);
	        	SysItemPlace::deleteAll(['item_id' => $model->id]);
	        	SysItemSery::deleteAll(['item_id' => $model->id]);
	        	
	        	$this->add_ext($model->id, $model->color_list, $model->style_list, $model->space_list, $model->place_list, $model->sery_list);
	        	
	        	$new_class_id = $model->class_id;
	        	$new_brand_id = $model->brand_id;
	        	if(($old_class_id != $new_brand_id || $old_brand_id != $new_brand_id) && !empty($model->gjj_code))
	        	{
	        		$model_g = $this->findModel($id);
	        		$model_g->gjj_code = $this->update_gjj_code($id);
	        		$model_g->save();
	        	}
	        	$this->update_log($id);//单品更新log
	        		
	            return $this->redirect(['view', 'id' => $model->id]);
	        } else {
	        	
	        	if(!empty($model->class_id)){  //class_id不为空时
	        		$class_id = $model->class_id;
	        		$pid = GrpClass::findOne(['id'=>$class_id])->father;
	        		$ppid = GrpClass::findOne(['id'=>$pid])->father;
	        		
	        		$model->class1 = $ppid;
	        		$model->class2 = $pid;
	        		
	        	}
	        	if(strpos($model->class_id, '000000'))//只有二级
	        	{
	        		$model->class2 = $model->class_id;
	        		$model->class1 = GrpClass::findOne(['id'=>$model->class2])->father;
	        		$model->class_id = null;
	        	}
	        	
	            return $this->render('update', [
	                'model' => $model,
	          		
	            ]);
	        }

    }

    /**
     * Deletes an existing SysItem model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the SysItem model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return SysItem the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        $model = SysItem::findOne($id);
        if($model !== null){
        		return $model;
        }else{
        	throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    /**
     * ajax选择类别
     * @param unknown $id
     */
    public function actionSelectclass1($id)
    {
    	$option_class2 = '';
    	$option_class_id = '';
    	$result = GrpClass::findAll(['father'=>$id]);
    	if ($result) {
    		foreach ($result as $value) {
    			$option_class2 .= '<option value="' . $value['id'] . '">' . $value['name'] . '</option>';
    			if(!empty($value['id']))
    			{
    				$result2 = GrpClass::findAll(['father'=>$value['id']]);
    				if($result2){
    					foreach ($result2 as $value)
    					{
    						$option_class_id .= '<option value="' . $value['id'] . '">' . $value['name'] . '</option>';
    					}
    				}
    				else{
    					$option_class_id .= '<option value="0">暂无</option>';
    				}
    							
    			}
    		}
    	} else {
    		$option_class2 .= '<option value="0">暂无</option>';
    	}
    	$arr_option =  array('class2'=>$option_class2,'class_id'=>$option_class_id);
    	echo  json_encode($arr_option); //以json数据返回
    
    }
    /**
     * ajax选择类别
     * @param unknown $id
     */
    public function actionSelectclass2($id)
    {
    	$option = '';
    	$result = GrpClass::findAll(['father'=>$id]);
        if ($result) {
            foreach ($result as $value) {
                $option .= '<option value="' . $value['id'] . '">' . $value['name'] . '</option>';
            }
        } else {
            $option .= '<option value="0">暂无</option>';
        }

        echo $option;
        
    }
    
    /**
     * 
     * @param 根据品牌分类获取品牌 $id
     */
    public function actionSelectbrandbyheadgrp($id){
        $option = '';
        $result = GrpBrand::findAll(['head_grp'=>$id,'useing'=>1]);
        if ($result) {
            foreach ($result as $value) {
                $option .= '<option value="' . $value['id'] . '">' . $value['name'] . '</option>';
            }
        } else {
            $option .= '<option value="0">暂无</option>';
        }
        
        echo $option;
        
    }
    public function actionSelectsery($brand_id)
    {
    	$checkbox = '';
    	$result = GrpSery::findAll(['brand_id'=>$brand_id]);
    		if($result)
    		{
    			foreach ($result as $key => $value) {
    				$checkbox .= '<label><input type="checkbox" name="SysItem[sery_list][]" value="'.$value['id'].'">'.$value['name']."</label>";
    			}
    		}else{
    			$checkbox .= '暂无';
    		}
    		echo $checkbox;
    
    }
    public function actionImagedefault($id,$item_name,$class_name)
    {	 		
	    	$this->layout = 'main_small';
	    	$model = new UploadForm();
	    	$model->scenario = 'no_need_file_name';
	    	$model_item = SysItem::findOne(['id'=>$id]);
	    	
	    	if (Yii::$app->request->isPost) {
	    		$model->image_upload = UploadedFile::getInstance($model, 'image_upload');

	    		if ($model->image_upload && $model->validate()) {
	    			if(empty($model_item->img_url_id)){//新增
		    			$arr = Image::save_image_to_files($model,$class_name,$item_name,
                            'item_default_image_thumb',
                            'item_default_image_small',
                            null,
                            null,
                            null,
                            true);
		    			$model_item->img_url_id = $arr['img_url_id'];
		    			$model_item->img_thumb_id = $arr['img_thumb_id'];
		    			$model_item->img_small_id = $arr['img_small_id'];
		    			$model_item->save();
	    			}else{//更新
	    				Image::save_image_to_files($model,$class_name,$item_name,
                            'item_default_image_thumb',
                            'item_default_image_small',
                            $model_item->img_url_id,
                            $model_item->img_thumb_id,
                            $model_item->img_small_id,
                            true);
	    			}
	    			$this->update_log($id);    			
	    		}
	    	}
	    	
	    	return $this->render('imagedefault', [
	    			'model' => $model,
	    			'id'=>$id,
	    			]);
    }
    /*
     * 无损替换图片
     */
    public function actionUpdateImages($item_id)
    {
        $conf = [
            'mainPreviewImage'=>[
                'width'=>1600,
                'height'=>1600,
            ],
            'mainPreviewImageM'=>[
                'width'=>800,
                'height'=>800,
            ],
            'mainPreviewImageS'=>[
                'width'=>400,
                'height'=>400,
            ],
            'tzImage'=>[
                'width'=>960,
                'height'=>720,
            ],
            'fabricImage'=>[
                'width'=>300,
                'height'=>300,
            ],
            'materialImage'=>[
                'width'=>300,
                'height'=>300,
            ]
        ];
        
        $item=SysItem::find()->joinWith([
            'defaultThumbImage',
            'preview.mainImageL',
            'preview.mainImageM',
            'preview.mainImageS',
            'preview.tzImage',
            'preview.fabric.fabricUrlImage',
            'preview.material.materialUrlImage'
        ])->where([SysItem::tableName().'.id'=>$item_id])->asArray()->one();
        
        $fab_id = explode(',', $item['fabric_list']);
        $mat_id = explode(',', $item['material_list']);
        
        $fab_arr = Fabric::find()->joinWith(['fabricUrlImage'])->where(['in',Fabric::tableName().'.id',$fab_id])->asArray()->all();
        $mat_arr = Material::find()->joinWith(['materialUrlImage'])->where(['in',Material::tableName().'.id',$mat_id])->asArray()->all();
        
        foreach ($item['preview'] as $i => $preview)
        {
            foreach ($fab_arr as $j => $fab)
            {
                if (!empty($preview['fabric']) && $fab['id'] == $preview['fabric']['id'])
                {
                    unset($fab_arr[$j]);
                }
            }
            foreach ($mat_arr as $j => $mat)
            {
                if (!empty($preview['material']) && $mat['id'] == $preview['material']['id'])
                {
                    unset($mat_arr[$j]);
                }
            }
        }
        
        foreach ($fab_arr as $fab)
        {
            $item['preview'][]=[
                'fabric'=>$fab
            ];
        }
        foreach ($mat_arr as $mat)
        {
            $item['preview'][]=[
                'material'=>$mat
            ];
        }
        
        $this->layout = 'main_small';
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            foreach ($post as $type => $arr)
            {
                if (in_array($type, ['mainPreviewImage','tzImage','fabricImage','materialImage'])){
                    foreach ($arr as $id => $value)
                    {
                        if ($value){
                            $img = Image::findOne(['id'=>$id]);
                            $img->imageFile = UploadedFile::getInstanceByName($type.'_'.$id);
                            if ($img->changeImageFile($conf[$type]['width'], $conf[$type]['height'])){
                                $img->save();
                                //生成中图小图
                                if ($type == 'mainPreviewImage'){
                                    $p = BaseSysPreview::find()->joinWith(['mainImageL','mainImageM','mainImageS'])->where(['img_url_id'=>$id])->one();
                                    $root = Yii::getAlias('@webroot/');
                                    $sourcePath = $img->url;
                                    if ($p->img_thumb_id != $p->img_url_id){
                                        $targetPath = $p->mainImageM->url;
                                        $newImg = Image::resizeImage($root, $sourcePath, $conf['mainPreviewImageM']['width'], $conf['mainPreviewImageM']['height'], $targetPath);
                                        $p->mainImageM->width = $newImg['width'];
                                        $p->mainImageM->height = $newImg['height'];
                                        $p->mainImageM->save();
                                    }
                                    if ($p->img_small_id != $p->img_url_id && $p->img_small_id != $p->img_thumb_id){
                                        $targetPath = $p->mainImageS->url;
                                        $newImg = Image::resizeImage($root, $sourcePath, $conf['mainPreviewImageS']['width'], $conf['mainPreviewImageS']['height'], $targetPath);
                                        $p->mainImageS->width = $newImg['width'];
                                        $p->mainImageS->height = $newImg['height'];
                                        $p->mainImageS->save();
                                    }
                                }
                                if ($type == 'fabricImage'){
                                    $p = Fabric::find()->joinWith(['fabricUrlImage','fabricThumbImage','fabricSmallImage'])->where(['img_url_id'=>$id])->one();
                                    $root = Yii::getAlias('@webroot/');
                                    $sourcePath = $img->url;
                                    if ($p->img_url_id != $p->img_thumb_id){
                                        $targetPath = $p->fabricThumbImage->url;
                                        $newImg = Image::resizeImage($root, $sourcePath, $conf['fabricImage']['width'], $conf['fabricImage']['height'], $targetPath);
                                        $p->fabricThumbImage->width = $newImg['width'];
                                        $p->fabricThumbImage->height= $newImg['height'];
                                        $p->fabricThumbImage->save();
                                    }
                                    if ($p->img_small_id != $p->img_url_id && $p->img_small_id != $p->img_thumb_id){
                                        $targetPath = $p->fabricSmallImage->url;
                                        $newImg = Image::resizeImage($root, $sourcePath, $conf['fabricImage']['width'], $conf['fabricImage']['height'], $targetPath);
                                        $p->fabricSmallImage->width = $newImg['width'];
                                        $p->fabricSmallImage->height= $newImg['height'];
                                        $p->fabricSmallImage->save();
                                    }
                                }
                                if ($type == 'materialImage'){
                                    $p = Material::find()->joinWith(['materialUrlImage','materialThumbImage','materialSmallImage'])->where(['img_url_id'=>$id])->one();
                                    $root = Yii::getAlias('@webroot/');
                                    $sourcePath = $img->url;
                                    if ($p->img_url_id != $p->img_thumb_id){
                                        $targetPath = $p->materialThumbImage->url;
                                        $newImg = Image::resizeImage($root, $sourcePath, $conf['materialImage']['width'], $conf['materialImage']['height'], $targetPath);
                                        $p->materialThumbImage->width = $newImg['width'];
                                        $p->materialThumbImage->height= $newImg['height'];
                                        $p->materialThumbImage->save();
                                    }
                                    if ($p->img_small_id != $p->img_url_id && $p->img_small_id != $p->img_thumb_id){
                                        $targetPath = $p->materialSmallImage->url;
                                        $newImg = Image::resizeImage($root, $sourcePath, $conf['materialImage']['width'], $conf['materialImage']['height'], $targetPath);
                                        $p->materialSmallImage->width = $newImg['width'];
                                        $p->materialSmallImage->height= $newImg['height'];
                                        $p->materialSmallImage->save();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return $this->render('_form_update_images',[
            'item'=>$item,
        ]);
    }
/**
 * 上传面料
 * @param unknown $id
 * @return Ambigous <string, string>
 */
  public function actionImagefabric($id)
    {	
	    	$this->layout = 'main_small';
	    	$model = new UploadForm();
	    	$model->scenario = 'need_file_name';
	    	$model_item = SysItem::findOne(['id' => $id]);
	
	    	$fabric_list = !empty($model_item->fabric_list)?$model_item->fabric_list:0;
	    	
	    	$name = '';
	    	if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
	    		$model->image_upload = UploadedFile::getInstance($model, 'image_upload');
	    		$name = $model->name;
	    		if ($model->image_upload && $model->validate()) {
	    			$fabric_menu = '188';
	    			$if_exist_model = Material::findBySql("select * from base_sys_fabric where name='{$name}'  and id in({$fabric_list})")->one();
	    			
	    			if(empty($if_exist_model)){
	    			$arr = Image::save_image_to_files($model,$fabric_menu,$name,'item_fabric_image_thumb','item_fabric_image_small');		
	    			$fabric_id = $this->newfabric($name, $arr['img_url_id'], $arr['img_small_id'], $arr['img_thumb_id']);
	    			$this->item_fabric($id, $fabric_id);
	    			}else{
	    				Image::save_image_to_files($model,$fabric_menu,$name,'item_fabric_image_thumb','item_fabric_image_small',$if_exist_model->img_url_id,$if_exist_model->img_thumb_id,$if_exist_model->img_small_id);
	    			}
	    			$this->update_log($id); 			
	    		}
	    	}
	    	
	    	return $this->render('imagefabric', [
	    			'model' => $model,
	    			'id' => $id,
	    			
	    			]);
    }
    //*新增fabric并获取id
    public function newfabric($name,$img_url_id,$img_small_id,$img_thumb_id)
    {
		$model = new Fabric();
		$model->name = $name;
		$model->img_url_id = $img_url_id;
		$model->img_thumb_id = $img_thumb_id;
		$model->img_small_id = $img_small_id;
		
    	if($model->save())
    	{  	   	 
			return $model->id;
    	}
    }
    //在sys_item中添加加入新的fabric_list
    public function item_fabric($id,$fabric_id)
    {
    	$model = SysItem::findOne(['id' => $id]);
    	//$model->fabric_list = !empty($model->fabric_list) ? $model->fabric_list.','.$fabric_id : (string)$fabric_id;
		$model->fabric_list = $this->add_list($model->fabric_list, (string)$fabric_id);
    	if($model->save())
    	{
    		return true;
    	}
    	
    }
    /**
     * 新增材质
     * @param unknown $id
     * @return Ambigous <string, string>
     */
    public function actionImagematerial($id)
    {

	    	$this->layout = 'main_small';
	    	$model = new UploadForm();
	    	$model->scenario = 'need_file_name';
	    	$model_item = SysItem::findOne(['id' => $id]);
	    	
	    	$material_list = !empty($model_item->material_list)?$model_item->material_list:0;
	  		
	    	$name = '';
	    	if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
	    		$model->image_upload = UploadedFile::getInstance($model, 'image_upload');
	    		$name = $model->name;
	    		if ($model->image_upload && $model->validate()) {
	    			$if_exist_model = Material::findBySql("select * from base_sys_material where name='{$name}' and id in({$material_list})")->one();
	    			if(empty($if_exist_model)){
	    				$arr = Image::save_image_to_files($model,'187',$name,'item_material_image_thumb','item_material_image_small');
	    				$material_id = $this->newmaterial($name, $arr['img_url_id'], $arr['img_small_id'], $arr['img_thumb_id']);
	    				$this->item_material($id, $material_id);
	    			}else{
	    				Image::save_image_to_files($model,'187',$name,'item_material_image_thumb','item_material_image_small',$if_exist_model->img_url_id,$if_exist_model->img_thumb_id,$if_exist_model->img_small_id);
	    			}
	    			$this->update_log($id);
	               
	    		}
	    	}
	    	 
	    	return $this->render('imagematerial', [
	    			'model' => $model,
	    			'id' => $id,
	    			 
	    			]);	
    }
    //*新增material并获取id
    public function newmaterial($name,$img_url_id,$img_small_id,$img_thumb_id)
    {
    	$model = new Material();
    	$model->name = $name;
    	$model->img_url_id = $img_url_id;
    	$model->img_thumb_id = $img_thumb_id;
    	$model->img_small_id = $img_small_id;
    
    	if($model->save())
    	{
    		return $model->id;
    	}
    }
    //在sys_item中添加加入新的material_list
    public function item_material($id,$material_id)
    {
    	$model = SysItem::findOne(['id' => $id]);
    	//$model->material_list = !empty($model->material_list) ? $model->material_list.','.$material_id : (string)$material_id;
    	$model->material_list = $this->add_list($model->material_list, (string)$material_id);
    	
    	if($model->save())
    	{
    		return true;
    	}
    	 
    }
/**
 * 面料--材质关系对应图
 * @param unknown $id
 * @return Ambigous <string, string>
 */
   public function actionImagefm($item_id,$item_name,$class_name)
    {

	    	$this->layout = 'main_small';
	    	$model = new UploadForm();
	    	$model->scenario = 'item_preview';
	    	
	    	if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
	    		$model->image_upload = UploadedFile::getInstance($model, 'image_upload');
	    		 
	    		if ($model->image_upload && $model->validate()) {
	    			if(empty($model->fid) && empty($model->mid))
	    			{
	    				echo  '<span class="btn btn-info">面料或材质需选择一个</span>';
	    				//return false;
	    					
	    			}
	    			if(!empty($model->fid)||!empty($model->mid))
	    			{		
			    		//材质面料对应主图已有，则修改主图
	    				//$_if_exist_fm = ItemPreview::findOne(['item_id'=>$model->item_id,'fid'=>$model->fid,'mid'=>$model->mid]);
						$sql_where = " item_id=".$model->item_id." and (fid=0 or fid is null or fid=".$model->fid.
	    														") and (mid=0 or mid is null or mid=".$model->mid.")"; 
	    				
						$_if_exist_fm = ItemPreview::findBySql("select * from base_sys_preview where ".$sql_where)->one();
					
	    				if($_if_exist_fm != null){
	    					$model_preview = $_if_exist_fm;
	    					$arr = Image::save_image_to_files($model,$class_name,$item_name,
                                'item_fm_image_thumb',
                                'item_fm_image_small',
                                $model_preview->img_url_id,
                                $model_preview->img_thumb_id,
                                $model_preview->img_small_id,
                                true); //存入文件并获得sys_image地址
	    				}else{
	    					$arr = Image::save_image_to_files($model,$class_name,$item_name,
                                'item_fm_image_thumb',
                                'item_fm_image_small',
                                null,
                                null,
                                null,
                                true); //存入文件并获得sys_image地址
	    					$model_preview = new ItemPreview();
	    					$model_preview->img_url_id = $arr['img_url_id'];
	    					$model_preview->img_thumb_id = $arr['img_thumb_id'];
	    					$model_preview->img_small_id = $arr['img_small_id'];
	    					$model_preview->item_id=$model->item_id;
	    					$model_preview->fid=$model->fid;
	    					$model_preview->mid=$model->mid;
	    					$model_preview->save();
	    				}    
	    				$this->update_log($item_id);
	    			}
	    		}
	    	}
	    
	    	return $this->render('imagefm', [
	    			'model' => $model,
	    			'item_id'=>$item_id,
	    			'item_name'=>$item_name,
	    			]);	
   }
/**
 * 
 * @param unknown $pid
 * @return Ambigous <string, string>
 */
    public function actionImagefmangle($pid,$item_id,$item_name,$class_name)
    {
    	$this->layout = 'main_small';
    	$model = new UploadForm();
    	$model->scenario = 'item_preview_angle';
    
    	if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
    		$model->image_upload = UploadedFile::getInstance($model, 'image_upload');
    		 
    		if ($model->image_upload && $model->validate()) {
    
    			$arr = Image::save_image_to_files($model,$class_name,$item_name,
                    'item_fmangle_image_thumb',
                    'item_fmangle_image_small',
                    null,
                    null,
                    null,
                    true); //存入文件并获得sys_image地址
    			
    			$model_fmangle = new ItemPreviewAngle();
    			
    			$model_fmangle->img_url_id = $arr['img_url_id'];
    			$model_fmangle->img_thumb_id = $arr['img_thumb_id'];
    			$model_fmangle->img_small_id = $arr['img_small_id'];
    			$model_fmangle->pid = $pid;
    			    
    			if($model_fmangle->save())
    			{
					$this->update_log($item_id);
					$this->redirect(['imagefm','item_id'=>$item_id,'item_name'=>$item_name,'class_name'=>$class_name]);
    			}
    			else
    			{
    				//echo '上传失败';
    			} 
    		}
    	}
    
    	return $this->render('imagefmangle', [
    			'model' => $model,
    			//'pid'=>$pid,
    			]);
    }
    

   /**
    * 透视图上传，更改，替换（不更改id和类别）
    * @param unknown $pid
    * @param unknown $item_id
    * @param unknown $item_name
    * @param unknown $class_name
    * @return Ambigous <string, string>
    */ 
        public function actionImagetz($pid,$item_id,$item_name,$class_name,$image_id=0)
    {
    	$this->layout = 'main_small';
    	$model = new UploadForm();
    	$model->scenario = 'item_preview_tz';
    	
    	if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
    		$model->image_upload = UploadedFile::getInstance($model, 'image_upload');
    		 
    		if ($model->image_upload && $model->validate()) {
    			
    			$model_fm = ItemPreview::findOne(['id' => $pid]);
    			//$image_id = $model_fm->img_tz_id;
    			if(empty($image_id))
    			{
    				$arr = Image::save_image_to_files($model,$model->image_typeid,$item_name,'item_fmtz_image_thumb','item_fmtz_image_small'); //存入文件并获得sys_image地址
    				$model_fm->img_tz_id = $arr['img_url_id'];
    				$model_fm->save();
    			}else{
    				$model_url_image = Image::findOne(['id'=>$image_id]);//找到url图片
    				$addr_url = $model_url_image->url;
    				$_arr = explode('.', $addr_url);
    				$addr_thumb = $_arr[0].'_1.'.$_arr[1];
    				$addr_small = $_arr[0].'_2.'.$_arr[1];
					
					$model_thumb = Image::findOne(['url'=>$addr_thumb]);
    				$model_small = Image::findOne(['url'=>$addr_small]);
    				$model_thumb_image = !empty($model_thumb)?$model_thumb->id:0;
    				$model_small_image = !empty($model_small)?$model_small->id:0;
					
    				Image::save_image_to_files($model,$model->image_typeid,$item_name,'item_fmtz_image_thumb','item_fmtz_image_small',$image_id,$model_thumb_image,$model_small_image);
    			}			
    			$this->update_log($item_id);
    			//删除cookies值
    			$cookies = Yii::$app->response->cookies;
    			unset($cookies['image_typeid']);
    			$this->redirect(['imagefm','item_id'=>$item_id,'item_name'=>$item_name,'class_name'=>$class_name]);

    		}
    	}
    
    	return $this->render('imagetz', [
    			'model' => $model,
    			//'pid'=>$pid,
    			]);
    }
    
    /**
     * 共用--存入数据到文件夹，并获取缩略图，三种图片的id
     * 压缩比例通过配置表设置
     * @param unknown $model
     * @param number $width1
     * @param number $height1
     * @param number $width2
     * @param number $height2
     * @return multitype:string boolean Ambigous <boolean, number>
     */
    public function save_image_to_files($model,$file_menu,$image_name,$thumb_type,$small_type)
    {
    	

    	$uuid = md5(uniqid());
    	$uuid_a =  substr($uuid, 0,3);
    	$uuid_b =substr($uuid, 3,3);
    	$uuid_c = substr($uuid, 6,3);
    	$uuid_d =  substr($uuid, 9,3); 	 
    	$uuid_file_name =  substr($uuid, 12,20); 	 
    	$folder = Yii::getAlias('@webroot').'/images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d;
    	TextSmser::make_dir($folder);
    	   	
    	$file_save_addr = 'images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d.'/'.$uuid_file_name; //实际位置   	 
    	$model->file->saveAs(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension);
    	if(!empty($model->name)){$image_name = $model->name; }   	
    	
    	$image_addr = $file_save_addr.'.'.$model->file->extension;
    	$image_url = $file_menu;
    	$image_w = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension)[0];
    	$image_h = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension)[1];
    
    	$img_url_id = $this->newimage($image_name,$image_addr, $file_menu, $image_w, $image_h);
    	$img_show = '<img style="margin:20px 10px 0px 0px;width:30%;" src="'.Yii::getAlias('@web').'/'.$file_save_addr.'.'.$model->file->extension.'">';
    	$img_url = $file_save_addr.'.'.$model->file->extension; 
    	
    	$thumb_ratio = PrfConfig::get_config_value($thumb_type); //压缩的比例
    	$small_ratio = PrfConfig::get_config_value($small_type); //压缩的比例
    	//生成缩略图并记录到数据库（中图）,大于990的时候
    	//if( $image_w / 2 >= 990)
    	if( $thumb_ratio >0 )
    	{	    
    		$thumb = new GD(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension); //原图
	    	//$thumb->resize($width1,$height1);
	    	$thumb->resizePercent($thumb_ratio);
	    	$file_save_addr_thumb = $file_save_addr.'_1';//实际位置
	    	$thumb->save(Yii::getAlias('@webroot').'/'.$file_save_addr_thumb.'.'.$model->file->extension);
	    
	    	$image_addr_thumb = $file_save_addr_thumb.'.'.$model->file->extension;
	    	$image_url_thumb = $file_menu;//虚拟目录（图片类别）
	    	$image_w_thumb = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_thumb.'.'.$model->file->extension)[0];
	    	$image_h_thumb = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_thumb.'.'.$model->file->extension)[1];
	    
	    	$img_thumb_id = $this->newimage($image_name.'_thumb',$image_addr_thumb, $file_menu, $image_w_thumb, $image_h_thumb);
	    	$img_show .= '<img style="margin:20px 10px 0px 0px;" src="'.Yii::getAlias('@web').'/'.$file_save_addr_thumb.'.'.$model->file->extension.'">';
	    	$img_thumb_url = $file_save_addr_thumb.'.'.$model->file->extension;
    	}
    	else 
    	{
    		$img_thumb_id = $img_url_id;
    	}

    	
    	//生成缩略图并记录到数据库（小图）
    	//if( $image_w /4 >=  300)
    	if( $small_ratio >0 )
    	{
	    	//$thumb->resize($width2,$height2);
	    	$small = new GD(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension);//原图
	    	$small->resizePercent($small_ratio);
	    	$file_save_addr_small = $file_save_addr.'_2';//实际位置
	    	$small->save(Yii::getAlias('@webroot').'/'.$file_save_addr_small.'.'.$model->file->extension);
	        
	    	$image_addr_small = $file_save_addr_small.'.'.$model->file->extension;
	    	$image_url_small = $file_menu;//虚拟目录（图片类别）
	    	$image_w_small = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_small.'.'.$model->file->extension)[0];
	    	$image_h_small = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_small.'.'.$model->file->extension)[1];
	    
	    	$img_small_id = $this->newimage($image_name.'_small',$image_addr_small, $file_menu, $image_w_small, $image_h_small);
	    	$img_show .= '<img style="margin:20px 10px 0px 0px;" src="'.Yii::getAlias('@web').'/'.$file_save_addr_small.'.'.$model->file->extension.'">';
	    	$img_show = '<div style="text-align:center;'.'">'.$img_show.'</div><div style="text-align:center;color:green;font-weight:bold;font-size:15px;">上传成功！</div>';
	    	$img_small_url = $file_save_addr_small.'.'.$model->file->extension;
	    	
    	}
    	else
    	{
    		$img_small_id= $img_url_id;
    	}
    	 
    	return array('img_url_id'=>$img_url_id,'img_thumb_id'=>$img_thumb_id,'img_small_id'=>$img_small_id,'img_show'=>$img_show);
    	 
    }
    /**
     * 共用-在数据表sys_image写入新图片
     * @param unknown $image_addr
     * @param unknown $image_url
     * @param unknown $image_w
     * @param unknown $image_h
     * @return boolean
     */
	     public function newimage($image_name,$image_addr,$file_menu,$image_w,$image_h)
    {
    	$model_image = new Image();
    	$model_image->name = $image_name;
    	$model_image->url = $image_addr;
    	$model_image->type = $file_menu;
    	$model_image->width = $image_w;
    	$model_image->height = $image_h;
		$model_image->update_time = time();
    	if($model_image->save())
    	{
    		return $model_image->id;
    		
    	}
    }

	
	 /**
     * 修改套装透视图的图片
     * @param unknown $model
     * @param unknown $file_menu 图片的类别
     * @param unknown $image_name 图片名称
     * @param unknown $thumb_type 中图压缩比例
     * @param unknown $small_type  小图压缩比例
     * @return multitype:string Ambigous <unknown, boolean> Ambigous <boolean, number>
     */
    public function update_image_for_imagetz($model,$file_menu,$image_name,$thumb_type,$small_type,$image_url_id)
    {
    	$model_url_image = Image::findOne(['id'=>$image_url_id]);//找到url图片
    	$addr_url = $model_url_image->url;
    	$_arr = explode('.', $addr_url);
    	$addr_thumb = $_arr[0].'_1.'.$_arr[1];
    	$addr_small = $_arr[0].'_2.'.$_arr[1];
    	
    	$model_thumb_image = Image::findOne(['url'=>$addr_thumb]);
    	$model_small_image = Image::findOne(['url'=>$addr_small]);
     	var_dump($model_thumb_image);
    	
    	$uuid = md5(uniqid());
    	$uuid_a =  substr($uuid, 0,3);
    	$uuid_b =substr($uuid, 3,3);
    	$uuid_c = substr($uuid, 6,3);
    	$uuid_d =  substr($uuid, 9,3);
    	$uuid_file_name =  substr($uuid, 12,20);
    	$folder = Yii::getAlias('@webroot').'/images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d;
    	TextSmser::make_dir($folder);
    		
    	$file_save_addr = 'images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d.'/'.$uuid_file_name; //实际位置
    	$model->file->saveAs(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension);
    	if(!empty($model->name)){$image_name = $model->name; }
    	 
    	$image_addr = $file_save_addr.'.'.$model->file->extension;
    	$image_url = $file_menu;
    	$image_w = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension)[0];
    	$image_h = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension)[1];
    	
    	$model_url_image->type = $file_menu;//图片分类
    	$model_url_image->name = $image_name;//图片名称
    	$model_url_image->url = $image_addr;//图片地址
    	$model_url_image->width = $image_w;
    	$model_url_image->height = $image_h;
    	$model_url_image->save();
    	
    	$thumb_ratio = PrfConfig::get_config_value($thumb_type); //压缩的比例
    	$small_ratio = PrfConfig::get_config_value($small_type); //压缩的比例
    	//生成缩略图并记录到数据库（中图）,大于990的时候
    	if( $thumb_ratio >0 )
    	{
    		$thumb = new GD(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension); //原图
    		//$thumb->resize($width1,$height1);
    		$thumb->resizePercent($thumb_ratio);
    		$file_save_addr_thumb = $file_save_addr.'_1';//实际位置
    		$thumb->save(Yii::getAlias('@webroot').'/'.$file_save_addr_thumb.'.'.$model->file->extension);
    	  
    		$image_addr_thumb = $file_save_addr_thumb.'.'.$model->file->extension;
    		$image_w_thumb = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_thumb.'.'.$model->file->extension)[0];
    		$image_h_thumb = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_thumb.'.'.$model->file->extension)[1];
    	  
    		if($model_thumb_image != null){
    			$model_thumb_image->type = $file_menu;//图片分类
    			$model_thumb_image->name = $image_name.'_thumb';//图片名称
    			$model_thumb_image->url = $image_addr_thumb;//图片地址
    			$model_thumb_image->width = $image_w_thumb;
    			$model_thumb_image->height = $image_h_thumb;
    			$model_thumb_image->save();
    		}else{//如果以前没有取中图，现在另存
    			$img_thumb_id = $this->newimage($image_name.'_thumb',$image_addr_thumb, $file_menu, $image_w_thumb, $image_h_thumb);
    		}
    	}  	 
    	//生成缩略图并记录到数据库（小图）  	
    	if( $small_ratio >0 )
    	{
    		//$thumb->resize($width2,$height2);
    		$small = new GD(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension);//原图
    		$small->resizePercent($small_ratio);
    		$file_save_addr_small = $file_save_addr.'_2';//实际位置
    		$small->save(Yii::getAlias('@webroot').'/'.$file_save_addr_small.'.'.$model->file->extension);
    		 
    		$image_addr_small = $file_save_addr_small.'.'.$model->file->extension;
    		$image_w_small = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_small.'.'.$model->file->extension)[0];
    		$image_h_small = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_small.'.'.$model->file->extension)[1];
    	  
    		if($model_small_image != null){
    			$model_small_image->type = $file_menu;//图片分类
    			$model_small_image->name = $image_name.'_small';//图片名称
    			$model_small_image->url = $image_addr_small;//图片地址
    			$model_small_image->width = $image_w_small;
    			$model_small_image->height = $image_h_small;
    			$model_small_image->save();
    			}else{//如果以前没有取中图，现在另存			
    				$img_small_id = $this->newimage($image_name.'_small',$image_addr_small, $file_menu, $image_w_small, $image_h_small);
    			}  
    	}
		return true;	
    }
	
    /**
     * 删除默认图片，删除sys_item表中的记录
     * @param unknown $item_id
     * @return boolean
     */
    public function actionDeleteDefault($item_id)
    {
    	$model_item = SysItem::findOne(['id'=>$item_id]);
    	$model_item->img_url_id = 0;
    	$model_item->img_thumd_id = 0;
    	$model_item->img_small_id = 0; 
    	if($model_item->save())
    	{
    	//var_dump($model_item);
    		$this->update_log($item_id);  		
    	} 
    	return true;    
    }
    /**
     * 删除面料，及各表的数据
     * @param unknown $fabric_id
     * @param unknown $item_id
     * @return boolean
     */
	 public function actionDeleteFabric($fabric_id,$item_id)
    {
    
    	$model_item = SysItem::findOne(['id'=>$item_id]);
    	$model_item->fabric_list = $this->delete_list($model_item->fabric_list,(string)$fabric_id);//删除对应
    	$model_item->save();
		$this->update_log($item_id);
    	 
    	$model_fabric = Fabric::findOne(['id'=>$fabric_id]);//删除fabric表
    	if(!empty($model_fabric->img_small_id))$this->delete_image($model_fabric->img_small_id,'Fabric',$model_fabric->id);
    	if(!empty($model_fabric->img_thumb_id))$this->delete_image($model_fabric->img_thumb_id,'Fabric',$model_fabric->id);
    	if(!empty($model_fabric->img_url_id))$this->delete_image($model_fabric->img_url_id,'Fabric',$model_fabric->id);
    	$model_fabric->delete();
    	 
    	$this->delete_preview('fid', $fabric_id, $item_id);
    	$this->delete_price('fabric_id', $fabric_id, $item_id);
    
    	return true;
    	 
    }
    public function actionDeleteMaterial($material_id,$item_id)
    {
    	$model_item = SysItem::findOne(['id'=>$item_id]);
    	$model_item->material_list = $this->delete_list($model_item->material_list, (string)$material_id);//删除在sys_item表的对应关系
    	$model_item->save();
		$this->update_log($item_id);
		
    	$model_material = Material::findOne(['id'=>$material_id]);//删除material表
    	if(!empty($model_material->img_small_id))$this->delete_image($model_material->img_small_id,'Material',$model_material->id);
    	if(!empty($model_material->img_thumb_id))$this->delete_image($model_material->img_thumb_id,'Material',$model_material->id);
    	if(!empty($model_material->img_url_id))$this->delete_image($model_material->img_url_id,'Material',$model_material->id);
    	$model_material->delete();
		
    	$this->delete_preview('mid', $material_id, $item_id);
    	$this->delete_price('material_id', $material_id, $item_id);
    
    	return true;
    
    }
    /**
     * 修改尺寸
     */
    public function actionUpdateSize($size_id,$size_name){
        
        $sysitemsize=SysItemSize::findOne($size_id);
        $sysitemsize->size=$size_name;
        $sysitemsize->save();
        return  "1"; exit();
    }
    /**
     * 删除尺寸
     * @param   $size_id
     * @param   $item_id
     * @return string
     */
    public function actionDeleteSize($size_id,$item_id)
    {
    	SysItemSize::findOne($size_id)->delete();
    	 $this->delete_price('size_id', $size_id, $item_id);
		  $this->update_log($item_id);
    	return '1';//已删除
    }
    /**
     * 共用方法--删除材质，面料，规格
     * @param unknown $field
     * @param unknown $field_id
     * @param unknown $item_id
     */
    public function delete_price($field,$field_id,$item_id)
    {
    	$model = SysItemPrices::findAll(['item_id'=>$item_id,$field=>$field_id]);
    	if($model !== null)
    	{
    		foreach ($model as $value)
    		{
    			$this->delete_price_ex($value->id);
    		}
    		SysItemPrices::deleteAll(['item_id'=>$item_id,$field=>$field_id]);//删除价格主表
    	}
    	 
    }
    public function delete_price_ex($pid)
    {
    	$model = SysItemPricesEx::findAll(['price_id'=>$pid]);
    	if($model !== null)
    	{
    		SysItemPricesEx::deleteAll(['price_id' => $pid]);//删除价格扩展表
    	}
    }
    /**
     * 共用方法--删除材质，面料，规格
     * @param unknown $field
     * @param unknown $field_id
     * @param unknown $item_id
     */
    public function delete_preview($field,$field_id,$item_id)
    {
    	$model = ItemPreview::findAll(['item_id'=>$item_id,$field=>$field_id]);
    	if($model !== null)
    	{
    		foreach ($model as $value)
    		{
    			$this->delete_preview_angle($value->id);
    			 
    			if(!empty($value->img_small_id))$this->delete_image($value->img_small_id,'ItemPreview',$value->id);
    			if(!empty($value->img_thumb_id))$this->delete_image($value->img_thumb_id,'ItemPreview',$value->id);
    			if(!empty($value->img_url_id))$this->delete_image($value->img_url_id,'ItemPreview',$value->id);
    			if(!empty($value->img_tz_id))$this->delete_image($value->img_tz_id,'ItemPreview',$value->id);
    		}
    		ItemPreview::deleteAll(['item_id'=>$item_id,$field=>$field_id]);//删除所有的对应图
    	}
    }
    public function delete_preview_angle($pid)
    {
    	$model = ItemPreviewAngle::findAll(['pid'=>$pid]);
    	if($model !== null)
    	{
    		foreach ($model as $value)
    		{
    			if(!empty($value->img_small_id))$this->delete_image($value->img_small_id,'ItemPreviewAngle',$value->id);
    			if(!empty($value->img_thumb_id))$this->delete_image($value->img_thumb_id,'ItemPreviewAngle',$value->id);
    			if(!empty($value->img_url_id))$this->delete_image($value->img_url_id,'ItemPreviewAngle',$value->id);
    		}
    		ItemPreviewAngle::deleteAll(['pid'=>$pid]);//删除所有的多角度图
    	}
    }
    //删除图片及文件

	public function delete_image($image_id,$table,$primary_id)
    {
    	$_sql = "img_small_id =".$image_id." or img_thumb_id =".$image_id." or img_url_id =".$image_id;
    	$_sql_except = "("."img_small_id =".$image_id." or img_thumb_id =".$image_id." or img_url_id =".$image_id.") and id<>".$primary_id;
    	$_sql_1 = "img_small_id =".$image_id." or img_thumb_id =".$image_id." or img_url_id =".$image_id." or img_tz_id =".$image_id;
    	$_sql_1_except = "("."img_small_id =".$image_id." or img_thumb_id =".$image_id." or img_url_id =".$image_id." or img_tz_id =".$image_id.") and id<>".$primary_id; 
    	   	
    	$_model_1 = SysItem::findBySql("select * from sys_item where ".$_sql)->all();
    	$_model_2 = Fabric::findBySql("select * from base_sys_fabric where ".$_sql)->all();
    	$_model_3 = Material::findBySql("select * from base_sys_material where ".$_sql)->all();
    	$_model_4 = ItemPreview::findBySql("select * from base_sys_preview where ".$_sql_1)->all();
    	$_model_5 = ItemPreviewAngle::findBySql("select * from base_sys_preview_angle where ".$_sql)->all();
    	
    	if($table=="SysItem"){$_model_1 = SysItem::findBySql("select * from sys_item where ".$_sql_except)->all();}
    	if($table=="Fabric"){$_model_2 = Fabric::findBySql("select * from base_sys_fabric where ".$_sql_except)->all();}
    	if($table=="Material"){$_model_3 = Material::findBySql("select * from base_sys_material where ".$_sql_except)->all();}
    	if($table=="ItemPreview"){$_model_4 = ItemPreview::findBySql("select * from base_sys_preview where ".$_sql_1_except)->all();}
    	if($table=="ItemPreviewAngle"){$_model_5 = ItemPreviewAngle::findBySql("select * from base_sys_preview_angle where ".$_sql_except)->all();}
    	
    	if($_model_1 == null && $_model_2 == null && $_model_3 == null && $_model_4 == null && $_model_5 == null)
    	{
	    	$model = Image::findOne($image_id);
	    	if($model !== null){
	    		unlink(Yii::getAlias('@webroot').'/'.$model ->url);//删除文件
	    		$model->delete();//删除数据库
	    		return true;
	    	}
    	}
    }
/**
     * 在base_sys_previw删除记录，但是在base_sys_preview_angle有依赖关系
     * @param unknown $preview_id
     * @return boolean
     */
    public function actionDeletePreview($preview_id)
    {
    	$model = ItemPreview::findOne(['id'=>$preview_id]);
    	$model_angel = ItemPreviewAngle::findAll(['pid'=>$preview_id]);
    	$item_id = $model->item_id;
    	$fid = $model->fid;
    	$mid = $model->mid;
    	if($model_angel != null)
    	{
    		echo '需先删除依赖的其他角度照片';
    	}
    	else
    	{   		
    		if(!empty($model->img_small_id))$this->delete_image($model->img_small_id,'ItemPreview',$model->id); //检查是否存在，再删除图片
    		if(!empty($model->img_thumb_id))$this->delete_image($model->img_thumb_id,'ItemPreview',$model->id); //检查是否存在，再删除图片
    		if(!empty($model->img_url_id))$this->delete_image($model->img_url_id,'ItemPreview',$model->id); //检查是否存在，再删除图片
    		if(!empty($model->img_tz_id))$this->delete_image($model->img_tz_id,'ItemPreview',$model->id); //检查是否存在，再删除图片
    		if($model->delete())
    		{
    			$this->delect_price_by_preview($item_id, $fid, $mid);
    			$this->update_log($item_id);
    			echo '删除';
    			return true;
    		}
    	}
    }
    public function delect_price_by_preview($item_id,$fibric_id,$material_id)
    {
       	($fibric_id === null)?$_sql1 = "fabric_id is null":$_sql1 = "fabric_id =".$fibric_id;
       	($material_id === null)?$_sql2 = "material_id is null":$_sql2 = "material_id =".$material_id;
       	$model = SysItemPrices::findBySql("select * from sys_item_prices where item_id=".$item_id." and ".$_sql1." and ".$_sql2)->all();
    	if($model !== null)
    	{
    		foreach ($model as $value)
    		{
    			$this->delete_price_ex($value->id);
    			SysItemPrices::deleteAll(['id'=>$value->id]);//删除价格主表
    		}
    	}
    }
	
    /**
     * 删除其他角度图片
     * @param unknown $angle_id
     * @return boolean
     */
    public function actionDeleteAngle($angle_id)
    {
    	$model = ItemPreviewAngle::findOne(['id'=>$angle_id]);
    	
		$model_preview = ItemPreview::findOne($model->pid);    	
		
    	if(!empty($model->img_small_id))$this->delete_image($model->img_small_id,'ItemPreviewAngle',$model->id); //检查是否存在，再删除图片
    	if(!empty($model->img_thumb_id))$this->delete_image($model->img_thumb_id,'ItemPreviewAngle',$model->id); //检查是否存在，再删除图片
    	if(!empty($model->img_url_id))$this->delete_image($model->img_url_id,'ItemPreviewAngle',$model->id); //检查是否存在，再删除图片

    	if($model->delete()){
			$this->update_log($model_preview->item_id);
    		return true;
    	}

    }
    public function actionRelatedItem($item_id)
    {
	    	//$this->layout = 'main_small';
	    	$searchModel = new SysItemSearch();
	    	$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    	
	    	return $this->render('related-item', [
	    			'searchModel' => $searchModel,
	    			'dataProvider' => $dataProvider,
	    			]);
    }
    public function actionAddRelatedItem($item_id,$related_id)
    {
    	$model = SysItem::findOne(['id'=>$item_id]);
    	
    	$model->related_list = $this->add_list($model->related_list,$related_id);
    	 if($model->save()){
    		$this->update_log($item_id);
    	}
    } 
    public function actionDeleteRelatedItem($item_id,$related_id)
    {
    	$model = SysItem::findOne(['id'=>$item_id]);
    	//$model->related_list = strpos($model->related_list,','.$related_id)?str_replace(','.$related_id, '', $model->related_list):str_replace($related_id, '', $model->related_list);
    	
    	//if(strpos($model->related_list,','.$related_id)){str_replace(','.$related_id, '', $model->related_list);}
    	//if(strpos($model->related_list,$related_id)){str_replace($related_id, '', $model->related_list);}
    	
    	$model->related_list = $this->delete_list($model->related_list,$related_id);
    	if($model->save()){
    		$this->update_log($item_id);
    	}
    }
    /**
     * 添加值到list中，如果存在，则不添加
     * @param unknown $list
     * @param unknown $data
     * @return string
     */
    public function add_list($list,$data)
    {
    	
    	if(!empty($list))
    	{
    		$arr = explode(',', $list);
    		if(!in_array($data, $arr))
    		{
    			array_push($arr, $data);
    			return implode(',', $arr);
    		}
    		return $list;
    	}
		else 
		{
			return $data;
		}
    		
    }
    /**
     * 从list中删除值
     * @param unknown $list
     * @param unknown $data
     * @return string
     */
    public function delete_list($list,$data)
    {
    	$arr = explode(',', $list);
    	$arr_push = array();
    	
    	foreach ($arr as $value)
    	{
    		if($value != $data)
    		{
    			array_push($arr_push, $value);
    		}
    	}
    	return implode(',', $arr_push);
    }
    /**
     	待完善
     * @return Ambigous <string, string>
     */
    public function actionFileManage()
    {
    	$model = PrfType::find()->all();
    	//var_dump($model);
    	
    	////foreach ($model as $value)
    //	{
    		//$arr = explode('/', $value);
    		

   	//	}
    	return $this->render('file_manage',[
    			'model' => $model,
    			]);
    	
    }

    /**
     * 父框架报上各个图片上传的页面
     * @param unknown $id
     */
    public function actionImageitem($id){
    	$this->render('imageitem',[
    			'id' =>$id,
    			
    			]);
    }
    
     public function actionAddCustomPrice($item_id,$size_id,$fabric_id,$material_id,$price_custom=0,$price_discount=0,$price_cost=0,$price_ex=0)
    {
		($fabric_id == null)?$_sql_1 = "(fid=0 or fid is null)":$_sql_1="fid=".$fabric_id;
    		($material_id == null)?$_sql_2 = "(mid=0 or mid is null)":$_sql_2="mid=".$material_id;

		$model_preview = ItemPreview::findBySql("select * from base_sys_preview where item_id=".$item_id." and ".$_sql_1." and ".$_sql_2)->all();
    		if($model_preview == null)
    		{
    			return '4';//如果在preview中不存在
    		}

		$price_id = '';
		$price_ex_tag = false;
		if($size_id == null)$size_id=0;
		if($fabric_id == null)$fabric_id=0;
		if($material_id == null)$material_id=0;
		
		
    	$model_price = SysItemPrices::findAll([
    		'item_id'=>$item_id,
    		'size_id'=>$size_id,
    		'fabric_id'=>$fabric_id,
    		'material_id'=>$material_id
    		]
    	);
    	//存在主表，没有提交扩展值
    	if($model_price != null && empty($price_ex))
    	{
    		
    		$_id = '';
    		foreach($model_price as $value_1)
    		{
    			$_model_1 = SysItemPricesEx::findAll(['price_id' => $value_1->id]);
    			if($_model_1 == null)
    			{
    				
    				$_id = $value_1->id;
    				//return '12';
    				break;
    			}
    			
    		}
    		
    		$_model_2 = SysItemPrices::findOne(['id'=>$_id]);
    	    if($_model_2->price_custom == $price_custom && $_model_2->price_discount == $price_discount) return '3';//价格已存在
    		else{
    			$_model_2->price_custom = $price_custom;
    			$_model_2->price_discount = $price_discount;
    			$_model_2->price_cost = $price_cost;
    			$_model_2->save();
    			return '2';//价格已更改
    		}	
    		
    	}
    	//存在主表，且提交了扩展表的值
    	if($model_price != null && !empty($price_ex))
    	{
    		//获得相等的price_id
    		
    		foreach ($model_price as $value_model_price){
    			$_price_id = $value_model_price->id;
    			$_arr_ex = array();//初始化数组
    			$model_price_ex = SysItemPricesEx::findAll(['price_id' => $_price_id]);
    			foreach ($model_price_ex as $_value_price_ex)
    			{
    				$_ex_id = $_value_price_ex->price_ex_id;
    				$_ex_name = $_value_price_ex->price_ex_value;
    				$_string = implode('=', [$_ex_id,$_ex_name]);
    				array_push($_arr_ex, $_string);
    			}
    			$_string_ex = implode('@', $_arr_ex);
    		    if($_string_ex == $price_ex)
    		    {
    		    	$price_id = $_price_id;
    		    	break;//终止循环
    		    }	
	    			//比较扩展表

    		}
    		
    		if(!empty($price_id))
    		{   			
    			$_model_price = SysItemPrices::findOne(['id'=>$price_id]);
    			if($_model_price->price_custom == $price_custom && $_model_price->price_discount == $price_discount) return '3';//价格已存在
    			else{
    				$_model_price->price_custom = $price_custom;
    				$_model_price->price_discount = $price_discount;
    				$_model_price->price_cost = $price_cost;
    				$_model_price->save();
    				return '2';//价格已更改
    			}	
    		}
    		if(empty($price_id))
    		{
    			
    			$this->add_price($item_id, $size_id, $fabric_id, $material_id,$price_custom,$price_discount,$price_cost,$price_ex);
    		}
    		
    	}
    	//主表没有，直接添加
    	if($model_price == null)
    	{
    		
    		$this->add_price($item_id, $size_id, $fabric_id, $material_id,$price_custom,$price_discount,$price_cost,$price_ex);
	    }
		$this->update_log($item_id);
    }
    public function add_price($item_id,$size_id,$fabric_id,$material_id,$price_custom=0,$price_discount=0,$price_cost=0,$price_ex=0)
    {

    	$model = new SysItemPrices();
    	$model->item_id = $item_id;
    	$model->size_id = $size_id;
    	$model->fabric_id = $fabric_id;
    	$model->material_id = $material_id;
    	$model->price_custom = $price_custom;
    	$model->price_discount = $price_discount;
    	$model->price_cost = $price_cost;
    	if($model->save()){
    		$price_id = $model->id;	
    	}
    	
    	if(!empty($price_ex))
    	{
    		$_arr = explode("@", $price_ex);
    		foreach ($_arr as $value){
    			$_arr_arr = explode("=", $value);
    			$price_ex_id = $_arr_arr[0];
    			$price_ex_value = $_arr_arr[1];
    	
    			$model_price_ex = new SysItemPricesEx();
    			$model_price_ex->price_id = $price_id;
    			$model_price_ex->price_ex_id = $price_ex_id;
    			$model_price_ex->price_ex_value = $price_ex_value;
    			$model_price_ex->save();    	
    		}
    		return "1";//已新增价格
    	}
    }

    /**
     * 删除定制价格
     * @param unknown $id
     */
    public function actionDeleteCustomPrice($id)
    {

    	if (($model = SysItemPrices::findOne($id)) !== null) {
    		$price_id = $model->id;
			$item_id = $model->item_id;
    		$model->delete();//删除主表
			$this->update_log($item_id);
    		SysItemPricesEx::deleteAll('price_id = :price_id',[':price_id' => $price_id]);//删除扩展表
    	}
    	
    }
    /**
     * 修改定制价格
     * @param unknown $id
     */
    public function actionChangeCustomPrice($id,$price_custom,$price_discount)
    {
        $price_cost = Yii::$app->request->get('price_cost');
    	if (($model = SysItemPrices::findOne($id)) !== null) {
    		$model->price_custom = $price_custom;
    		$model->price_discount = $price_discount;
    		if (!empty($price_cost)) {
                $model->price_cost = $price_cost;
            }
			if($model->save()){
				echo true;
			}
    	}
    	echo false;
    	 
    }
    /**
     * 增加单品扩展信息
     * @param unknown $item_id
     * @param unknown $item_ex
     * @return string
     */
    public function actionAddItemInfoEx($item_id,$item_ex)
    {
    	$_arr = explode("@", $item_ex);
    	foreach ($_arr as $value)
    	{
    		$_arr_arr = explode("=", $value);
    		$ex_id = $_arr_arr[0];
    		$ex_value = $_arr_arr[1];
    		 
    		$model = SysItemInfoEx::findOne([
    				'item_id'=>$item_id,
    				'item_ex_id'=>$ex_id,
    				'item_ex_value'=>$ex_value,
    				]
    		);
    		if($model == null)
    		{
    			$model_new = new SysItemInfoEx();
    			$model_new->item_id = $item_id;
    			$model_new->item_ex_id = $ex_id;
    			$model_new->item_ex_value = $ex_value;
    			if($model_new->save())
    			{
					$this->update_log($item_id);
    				return '1';
    			}
    		}
    		if($model != null)return '2';
    	}
    }
    public function actionDeleteItemInfoEx($id)
    {
		$item_id = SysItemInfoEx::findOne($id)->item_id;
    	SysItemInfoEx::findOne($id)->delete();
		$this->update_log($item_id);
    }
    public function actionAddSize($item_id,$size_ex)
    {
    	$_arr = explode("@", $size_ex);
    	$_arr_1 = explode("=", $_arr[0]);//规格
    	$_arr_2 = explode("=", $_arr[1]);//体积
		$_arr_3 = explode("=", $_arr[2]);//毛重
    	
    	$_model = SysItemSize::findOne([
    			'item_id'=>$item_id,
    			$_arr_1[0]=>$_arr_1[1],
    			$_arr_2[0]=>$_arr_2[1],
				$_arr_3[0]=>$_arr_3[1],
    			]
    	);
    	$_model_1 = SysItemSize::findOne([
    			'item_id'=>$item_id,
    			$_arr_1[0]=>$_arr_1[1],    			
    			]);
    	if($_model === null && $_model_1 === null)
    	{
    		$model = new SysItemSize();
    		$model->item_id = $item_id;
    		$model[$_arr_1[0]]=$_arr_1[1];
    		$model[$_arr_2[0]]=$_arr_2[1];
			$model[$_arr_3[0]]=$_arr_3[1];
    		$model->save();
			$this->update_log($item_id);
    		return '1';//已新增
    	}
    	if($_model === null && $_model_1 !== null)
    	{
    		$_model_1[$_arr_2[0]]=$_arr_2[1];
			$_model_1[$_arr_3[0]]=$_arr_3[1];
    		$_model_1->save();
			$this->update_log($item_id);
    		return '2';//已更新体积和毛重
    	}
    	if($_model !== null)
    	{
    		return '3';//已存在
    	}
    }
    /**
     * 增加过++编码
     */
    public function actionAddGjjCode($id)
    {
		$model = SysItem::findOne(['id'=>$id]);
		if(empty($model->fabric_list) && empty($model->material_list))
    	{
    		return '2';
    	}
    	$date = date('ym',time());
    	
    	$factory_short_code =  $model->brand_name->brandFactory->short_code;
    	   	
    	$class2= '';
    	if(strpos($model->class_id, '000000'))//只有二级
    	{
    		$class2 = $model->class_id;
    	}else if(GrpClass::findOne(['id'=>$model->class_id]) != null){
    		$class2 = GrpClass::findOne(['id'=>$model->class_id])->father;//有三级
    	}
    	
    	$gjj_code_class2 =  str_pad(ceil($class2/1000000), 4, '0' ,STR_PAD_LEFT);
    	$gjj_code_id = str_pad($id, 11, '0' ,STR_PAD_LEFT);
    	
    	if($model->gjj_code == null)
    	{
    		$model->gjj_code = $date . $factory_short_code . $gjj_code_class2 . $gjj_code_id;
    		$model->app_return = '1';
    		if($model->save())
			{
				$this->update_log($id);
			}
    		return '过++代码设置成功';
    	}
    	//return '过++代码已存在';
    }
    public function update_gjj_code($id)
    {
    	$date = date('ym',time());
    	$model = SysItem::findOne(['id'=>$id]);
    	$factory_short_code =  $model->brand_name->brandFactory->short_code;
    	$class2= '';
    	if(strpos($model->class_id, '000000'))//只有二级
    	{
    		$class2 = $model->class_id;
    	}else if(GrpClass::findOne(['id'=>$model->class_id]) != null) {
    		$class2 = GrpClass::findOne(['id'=>$model->class_id])->father;//有三级
    	}
    	
    	$gjj_code_class2 =  str_pad(ceil($class2/1000000), 4, '0' ,STR_PAD_LEFT);
    	$gjj_code_id = str_pad($id, 11, '0' ,STR_PAD_LEFT);
    	return $date . $factory_short_code . $gjj_code_class2 . $gjj_code_id;
    }

	/**
 * 更新单品，记录uid和时间
 * @param unknown $id
 */    
    public function update_log($id)
    {
    	$model = SysItem::findOne(['id' => $id]);
    	if($model !== null){
	    	$model->update_uid = Yii::$app->user->identity->id;
	    	$model->update_at = time();
	    	$model->save();
    	}
    }
		/**
	 * 批量设置折扣价
	 * @param unknown $head_grp
	 */
	    public function actionSelectBrand($head_grp){
    	$model = GrpBrand::findAll(['head_grp'=>$head_grp]);
    	$selece_brand ='';
    	foreach ($model as $value){
    		$selece_brand .= '<label id="'.$value['id'].'"><input name="SysItem[brand_id_for_price][]" value="'.$value['id'].'" type="checkbox" checked="checked"></input>'.$value['name'].'</label>';
    	}
    	echo $selece_brand;
    	
    }
    public function actionDeleteBrand($head_grp){
    	$model = GrpBrand::findAll(['head_grp'=>$head_grp]);
    	$arr = array();
    	foreach ($model as $value)
    	{
    		array_push($arr, $value['id']);
    	}
    	//var_dump($arr);
    	return json_encode($arr);
    }
    /*设置全部的折扣价*/
    public function actionSetDiscountPriceBatch()
    {
    	$class_select = '';
    	$model = new SysItem();
    	if ($model->load(Yii::$app->request->post())) {

    		if(!empty($model->class_id)){$class_select = $model->class_id;}
    		else if(!empty($model->class2)){$class_select = $model->class2;}
    		else if(!empty($model->class1)){$class_select = $model->class1;}
    		 
    		if($model->price_batch_all == 1){//全选
    			SysItem::updateAll(['price_discount'=>$model->price_batch],'');
    		}elseif($class_select!=0){//类别
    			SysItem::updateAll(['price_discount'=>$model->price_batch],'class_id='.$class_select);
    		}elseif(!empty($model->brand_id_for_price)){//单个品牌
    			
    			foreach ($model->brand_id_for_price as $value){  				
    				SysItem::updateAll(['price_discount'=>$model->price_batch],'brand_id='.$value);
    			}  			
    		}
    		 return $this->redirect(['index']);
    	} else {
    		return $this->render('set_discount_price_batch', [
    				'model' => $model,
    				]);
    	}
    }
	    /*改变面料名称*/
    public function actionChangeFabric($fabric_id,$name)
    {
    	$model_fabric = Fabric::findOne(['id'=>$fabric_id]);
    	$model_fabric->name = $name;
    	if($model_fabric->save()){return true;}
    	return false;
    
    }
	    /*改变涂装名称*/
    public function actionChangeMaterial($material_id,$name)
    {   
    	$model_material = Material::findOne(['id'=>$material_id]);
    	$model_material->name = $name;
    	if($model_material->save()){return true;}
    	return false;
    
    }
	    /*修改涂装工艺*/
    public function actionChangeCoating($fm_id,$coating)
    {
    	$model_preview = ItemPreview::findOne(['id'=>$fm_id]);
    	$model_preview->coating = $coating;
    	if($model_preview->save()){return true;}
    	return false;
    }
    //生成单品二维码
    public function actionGenerateQrcode(){
    	
    	if(Yii::$app->request->isPost){
    		$ids = Yii::$app->request->post("ids");
    		if($ids){
    			foreach ($ids as $val){
    				SysItem::generateQRcode($val);
    			}
    		}
    		exit(json_encode(array('code'=>'1','msg'=>'已生成二维码')));
    	}
    }
    //下载二维码
    public function actionDownloadQrcode($QRcode){
		header('Content-type: application/png');  
		header('Content-Disposition: attachment; filename="'.md5($QRcode).'qrcode.png"');  
		readfile(Yii::getAlias('@webroot').'/'.$QRcode); 	
    }
    //批量生成二维码
    public function actionBatchQrcode(){
    	$model = SysItem::find()->where("QRcode <> ''")->limit(100)->all();
    	if($model){
    		foreach ($model as $val){
    			echo $val['id'];
    			SysItem::generateQRcode($val['id']);
    		}
    		$this->redirect(['batch-qrcode']);
    	}
    }
    // 删除单品
    public function actionDeleteSysItem() {
        if(Yii::$app->request->isPost || Yii::$app->request->isGet){
            $ids = Yii::$app->request->post("ids");
            $success  = array();
            $fail = array();
            $sysItemModel = new SysItem();
            if($ids){
                foreach ($ids as $val){
                    if($sysItemModel->deleteSysItem(intval($val))){
                        array_push($success, $val);
                    } else {
                        array_push($fail, $val."[".$sysItemModel->errMsg."]");
                    }

                }
            }
           exit(json_encode(array('code'=>'1','msg'=>'删除成功:'.implode(',', $success).'；删除失败:' . implode(',', $fail))));
        }
    }
    
    /** 用于ueditor插件
     * (non-PHPdoc)
     * @see \yii\base\Controller::actions()
     * by suiyue
     */
    public function actions(){
    	$actions = parent::actions();
    	$actions['upload'] = [
    					'class'=>'backend\widgets\ueditor\UEditorAction',
    					'config'=>[
    							'imageUrlPrefix'=>"https://".$_SERVER['SERVER_NAME']."/gjj/backend/web/images/",//图片访问路径前缀
			   					'imagePathFormat'=>'{rand:2}/{time}{rand:6}',
			   				    'imageRoot'=>\Yii::getAlias("images")
    					]
    			];
    	return $actions;
    }
    /**
     * 单品列表 导出功能展示
     */
    public function actionExportList(){ 
        $searchModel = new SysItemSearch();
        $queryParams=Yii::$app->request->queryParams;
        
        $searchModel->load($queryParams);
        $brand_id=intval($searchModel->brand_id);
        $app_return=$searchModel->app_return;
        if(!empty($app_return)){
            $app_return=implode(",", $app_return) ;
        }else{
            $app_return="0,1,2,3";
            $searchModel->app_return=array('0'=>'0','1'=>'1','2' => '2','3' => '3');
        }
        $connection = Yii::$app->db;
        if($brand_id>0){//根据条件查询单品
            $sql="
            SELECT m_image.url m_url,f_image.url f_url,base_item.id,base_item.factory_code,base_item.update_at,base_item.min_order_quantity,base_item.app_return,base_item.name,base_item.brand_name,
            base_item.item_thumb,  base_item.price_base,base_sys_material.name material_name,
            base_sys_fabric.name fabric_name,
            sys_item_price.size, sys_item_price.price_custom, base_item.price_base+sys_item_price.price_custom price
            FROM (
                SELECT sys_item.id,sys_item.`name`,sys_item.update_at,sys_item.min_order_quantity,sys_item.factory_code,sys_item.app_return,sys_item.brand_id,grp_brand.name brand_name,
                sys_image.url item_thumb , sys_item.price_base,base_sys_preview.fid,base_sys_preview.mid
                FROM  sys_item
                LEFT JOIN base_sys_preview   ON  sys_item.id = base_sys_preview.item_id
                LEFT JOIN   grp_brand  ON sys_item.`brand_id`=grp_brand.id
                LEFT JOIN    sys_image  ON  sys_item.`img_small_id`=sys_image.id
                WHERE  sys_item.id = base_sys_preview.item_id AND
                sys_item.app_return  in ($app_return)  AND sys_item.brand_id=$brand_id  AND sys_item.`brand_id`=grp_brand.id
                AND sys_item.`img_small_id`=sys_image.id
            )  base_item
            LEFT JOIN base_sys_material ON base_sys_material.id=base_item.mid
            left join sys_image m_image on m_image.id=base_sys_material.img_small_id

            LEFT JOIN base_sys_fabric ON base_sys_fabric.id=base_item.fid
            left join sys_image  f_image on f_image.id=base_sys_fabric.img_small_id

            LEFT JOIN (
                SELECT sys_item_prices.`item_id`,sys_item_prices.fabric_id,sys_item_prices.`material_id`,
                sys_item_prices.size_id,sys_item_prices.price_custom ,sys_item_size.`size`
                FROM
                sys_item_prices LEFT JOIN sys_item_size ON  sys_item_prices.`size_id`= sys_item_size.id
            )  sys_item_price
             ON  base_item.id = sys_item_price.item_id
            AND base_item.fid= sys_item_price.fabric_id AND base_item.mid = sys_item_price.material_id
            ORDER BY base_item.id
            ";
            $get_count= count($connection->createCommand($sql)->queryAll());
            
            //  $query=SysItem::findBySql($sql)->asArray();
        }else{
            $sql="select id from sys_item where 1>2";
            /*  $conditions = '1!=1';
             $query = SysItem::find()->where($conditions)
             ->select("sys_item.id"); */
            $get_count=0;
        }
        $command = $connection->createCommand($sql)->queryAll();
        $pages = new Pagination(['totalCount' => count($command),'defaultPageSize'=>10]);
        $list = $connection->createCommand($sql." limit ".$pages->limit." offset ".$pages->offset."")->queryAll();
        for($i=0;$i<count($list);$i++){
            
            if( $list[$i]['update_at']==0){
                $list[$i]['update_at']="";
            }else{
                $list[$i]['update_at']=date("Y-m-d H:i:s",$list[$i]['update_at']);
            }
            if( $list[$i]['min_order_quantity']==""){
                $list[$i]['min_order_quantity']="";
            } 
            if($list[$i]['price']==""){
                $list[$i]['price']=$list[$i]['price_base'];
            }
            if($list[$i]['price_base']==""){
                $list[$i]['price_base']=0;
            }
            if($list[$i]['price_custom']==""){
                $list[$i]['price_custom']=0;
            }
            if($list[$i]['material_name']==""){
                $list[$i]['material_name']="";
            }
            
            if($list[$i]['fabric_name']==""){
                $list[$i]['fabric_name']="";
            }
            if($list[$i]['size']==""){
                $list[$i]['size']="";
            }
            if($list[$i]['factory_code']==""){
                $list[$i]['factory_code']="";
            }
            $app_return=array('0'=>'编辑','1'=>'上架','2' => '下架','3' => '删除');
            $list[$i]['app_return']=$app_return[$list[$i]['app_return']];
        }
        $dataProvider = new ArrayDataProvider([
            'allModels' => $list,
        ]);
        $page_num=1;
        $offset=intval($pages->offset)+10;
        if(key_exists("page",$queryParams)){
            $page_num=intval($queryParams['page']);
            if($page_num>1){
                $limit=$page_num-1;
            }
            $limit=($page_num-1)*10+1;
        }else{
            $limit=1;
        }
        if($get_count==0){
            $limit=0;
        }
        if($get_count-$limit<10){
            $offset=$get_count;
        }
        return $this->render('export_index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'pages'=>$pages,
            'dataCount'=>$get_count,
            'limit'=>$limit,
            'offset'=>$offset
        ]);
    }
    
    /**
     * 导出单品
     */
    public function  actionExportData(){
        //test
        //test
        $post=Yii::$app->request->post();
        $system=$post['SysItem'];
        $brand_id=intval($system['brand_id']);
        $brand=GrpBrand::findOne($brand_id);
        $app_return_array=$system['app_return'];
        if(!empty($app_return_array)){
            $app_return=implode(",", $system['app_return']) ;
        }else{
            $app_return="0,1,2,3";
        }
        //单品根据分类以及单品的状态进行查询导出 
       $sql="
        SELECT base_item.id,base_item.name,base_item.brand_name,
         base_item.item_thumb,  base_item.price_base,base_sys_material.name material_name,
        base_sys_fabric.name fabric_name, 
         sys_item_price.size, sys_item_price.price_custom, base_item.price_base+sys_item_price.price_custom price
        FROM (
            SELECT sys_item.id,sys_item.`name`,sys_item.brand_id,grp_brand.name brand_name,
            sys_image.url item_thumb , sys_item.price_base,base_sys_preview.fid,base_sys_preview.mid
             FROM  sys_item 
            LEFT JOIN base_sys_preview   ON  sys_item.id = base_sys_preview.item_id 
    	    LEFT JOIN   grp_brand  ON sys_item.`brand_id`=grp_brand.id 
    	    LEFT JOIN    sys_image  ON  sys_item.`img_small_id`=sys_image.id
             WHERE  sys_item.id = base_sys_preview.item_id AND
             sys_item.app_return  in ($app_return)  AND sys_item.brand_id=$brand_id  AND sys_item.`brand_id`=grp_brand.id 
             AND sys_item.`img_small_id`=sys_image.id  
         ) base_item 
        LEFT JOIN base_sys_material ON base_sys_material.id=base_item.mid
        LEFT JOIN base_sys_fabric ON base_sys_fabric.id=base_item.fid
        LEFT JOIN  
                (
                SELECT sys_item_prices.`item_id`,sys_item_prices.fabric_id,sys_item_prices.`material_id`,
                sys_item_prices.size_id,sys_item_prices.price_custom ,sys_item_size.`size` 
        FROM 
                sys_item_prices LEFT JOIN sys_item_size ON  sys_item_prices.`size_id`= sys_item_size.id
                ) 
        sys_item_price ON  base_item.id = sys_item_price.item_id 
        AND base_item.fid= sys_item_price.fabric_id AND base_item.mid = sys_item_price.material_id
        ORDER BY base_item.id;
        ";
      $data=SysItem::findBySql($sql)->asArray()->all();
    /*   $posts = Yii::$app->db->createCommand($sql,$param)
      ->queryAll(); */
     
            //         if ($data)
                //         {
                //             //数据处理
                //         }
                    $header = ['单品ID', '名称', '品牌','主图', '基础价', '材质',  '面料',  '尺寸', '定制价（元）', '总金额（元）']; //导出excel的表头
                    ItemCommonFunc::exportData($data, $header,$brand['name']."价格表");
    }
    
   /**
    * 批量设置价格
    * @return string
    */
    public function actionUpdatePrice(){
        $model=SysItem::find()->orderBy("id desc")->limit(1)->one();
        if(Yii::$app->request->isPost){
            //修改
            $post=Yii::$app->request->post();
            $bs=$post['bs'];
            $brand_id=$post['brand_id'];
			//基础价
            $sql="UPDATE sys_item SET price_base=FLOOR(FLOOR(ROUND(price_cost*{$bs},2))/100)*100+99
                  WHERE brand_id={$brand_id} and price_cost>0";
            $num=Yii::$app->db->createCommand($sql)->execute();
			//定制价
            $num=Yii::$app->db->createCommand('UPDATE sys_item_prices A JOIN sys_item B ON A.item_id=B.id SET A.price_custom = ROUND(A.price_cost* :bs / 100+0.00001, 0)  * 100
                  WHERE B.brand_id=:brand_id and A.price_cost>0', [':bs' => $bs, ':brand_id'=>$brand_id])->execute();
            echo $num;exit();
            
        }else{
            //加载页面
            return $this->render('update_price', [
                'model' => $model,
            ]);
        }
    }
}

 